package cn.tedu.blog.server.repo.impl;


import cn.tedu.blog.server.pojo.vo.ArticleStandardVO;
import cn.tedu.blog.server.repo.IArticleRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Repository
public class ArticleRepository implements IArticleRepository {


    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;
    @Override
    public void put(ArticleStandardVO articleStandardVO) {

    }

    @Override
    public ArticleStandardVO get(Long id) {

        return null;
    }

    @Override
    public void deleteItem(Long id) {

    }

    @Override
    public void putList(List<ArticleStandardVO> list,String key) {
        log.debug("向Redis中写入品牌列表数据：{}", list);
        for (ArticleStandardVO articleStandardVO : list) {
            redisTemplate.opsForList().rightPush(key, articleStandardVO);
        }
        switch (key){
            case KEY_NEWEST_ARTICLE_LIST:
                redisTemplate.expire(key,1L,TimeUnit.MINUTES);
                break;
            case KEY_POPULAR_ARTICLE_LIST:
                redisTemplate.expire(key,1L,TimeUnit.DAYS);
                break;
            case KEY_IS_RECOMMEND_ARTICLE_LIST:
                redisTemplate.expire(key,1L,TimeUnit.DAYS);
                break;
        }

    }
    public List<ArticleStandardVO> getList(String key) {
        log.debug("即将从Redis中读取品牌列表数据……");
        List<Serializable> list = redisTemplate.opsForList().range(key, 0, -1);
        List<ArticleStandardVO> articleList = new ArrayList<>();
        for (Serializable serializable : list) {
            articleList.add((ArticleStandardVO) serializable);
            log.debug("从Redis中读取到的品牌列表：{}", articleList);
        }
        return articleList;
    }
    @Override
    public void deleteList() {

    }
    @Override
    public boolean  isExpired(String key) {
       Long expiredTime= redisTemplate.getExpire(key);
        log.debug("密钥有效时间：{}",expiredTime);
       if(expiredTime==-2){
           return true;
       }
        return false;
    }


}
